import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './activitybm.scss'

export default class Index extends Component {

	constructor(props) {
    super(props);
    this.state = {
      copies_num:1,//预定份数
      copies_img:'https://minichat.g2ma.com/kedouimg/icon22.png',
      res:{},//活动详情
      isload:0,//判断页面是否加载完成
      userName:'',
      userPhone:0,
      remark:'',
      consumptionId:0,
      orderId:0,
      zftype:0,
      paypwd:[],
      paypwdlen:0,
      yhqname:'',
      verificationCode:'',
      tuitable:[{number:'1',tuibg:false,innerhtml:false,click:'1'},
                {number:'2',tuibg:false,innerhtml:false,click:'1'},
                {number:'3',tuibg:false,innerhtml:false,click:'1'},
                {number:'4',tuibg:false,innerhtml:false,click:'1'},
                {number:'5',tuibg:false,innerhtml:false,click:'1'},
                {number:'6',tuibg:false,innerhtml:false,click:'1'},
                {number:'7',tuibg:false,innerhtml:false,click:'1'},
                {number:'8',tuibg:false,innerhtml:false,click:'1'},
                {number:'9',tuibg:false,innerhtml:false,click:'1'},
                {number:'-',tuibg:true,innerhtml:false,click:'3'},
                {number:'0',tuibg:false,innerhtml:false,click:'1'},
                {number:'',tuibg:true,innerhtml:true,click:'2'}
              ],
      bmtetlist:[{touimg:'https://minichat.g2ma.com/kedouimg/icon26.png',touname:'推荐微信用户使用',toutype:'微信支付',toucheck:true,id:'1'},

                ],
        //{touimg:'https://minichat.g2ma.com/kedouimg/icon28.png',touname:'使用我的余额支付',toutype:'余额支付',toucheck:false,id:'2'},
      paytypes:1,//支付方试
      myTime:null,
      member:''
    }
  }

  config = {
    navigationBarTitleText: '加载中'
  }

  opendetails(url,id){
    this.$preload('activityId',id);
    CommonJs.openTo(url);
  }
  buzhichi(){
    Taro.showModal({
      title: '提示',
      content: '抱歉，小程序不允许你访问网页链接，如需获得最全功能和更好体验请下载“蝌蚪社区”APP!',
      showCancel: false
    })
  }
  addandsubtract (index) {
  	var _this = this;
  	var copies_num = _this.state.copies_num
  	if(index==0){
  		if(copies_num==1){
  			Taro.showToast({
				  title:'至少要预定一个啦！',
				  icon: 'none',
				  duration: 2000
				});
  		}else{
  			copies_num = copies_num - 1
  			_this.setState({
	        copies_num: copies_num
	     	});
	     	if(copies_num==1){
  				_this.setState({
		        copies_img:'https://minichat.g2ma.com/kedouimg/icon22.png'
		     	});
  			}
  		}
  	}else if(index==1){
  		copies_num = copies_num + 1
			_this.setState({
        copies_num: copies_num
     	});
     	if(copies_num==2){
				_this.setState({
		      copies_img:'https://minichat.g2ma.com/kedouimg/icon21.png'
		    });
			}
  	}
  }

  componentWillMount () {
    // console.log(this.$router.preload.activityId)
    this.getdata()
  }

  componentWillUnmount () {
    clearTimeout(this.myTime)
  }
  componentDidShow () {
  	
		var cindex="";
		var pages = getCurrentPages();
		var Page = pages[pages.length - 1];
		var info = Page.data;
		
		if(info){
			this.setState({
				verificationCode:info.yhq.ids,
         	    yhqname:info.yhq.name,
			})
		}
	
	}
  getmember(){
  	var url='/shop/papi/v1.9/members/account/'+Taro.getStorageSync('shopId')
  	var _this=this;
    CommonJs.ajaxRequest(url,'','GET',function(res){
        _this.setState({
          member: res.data,
        });
    },'wfw')
  }
  lijipay(){
    let _this = this
    let userName = _this.state.userName
    let userPhone = _this.state.userPhone
    let myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
    if (userName == '') {
      Taro.showToast({
        title:'请输入联系人姓名',
        icon: 'none',
        duration: 1000
      })
    } else if (userPhone == 0) {
      Taro.showToast({
        title:'手机号不能为空',
        icon: 'none',
        duration: 1000
      })
    } else if (userPhone.length < 11) {
      Taro.showToast({
        title:'手机号长度有误',
        icon: 'none',
        duration: 1000
      })
    } else if (!myreg.test(userPhone)) {
      Taro.showToast({
        title:'手机号有误',
        icon: 'none',
        duration: 1000
      })
    } else {
      var paytypes = _this.state.paytypes
      if (paytypes == 1) {
        Taro.login({
          success(res) {
            // console.log(JSON.stringify(res)+'aa1111')
            if (res.code) {
                _this.getbomn(res.code)
            } else {
                Taro.showToast({
                  title:'网络异常',
                  icon: 'none',
                  duration: 2000
                })
            }
          }
        })
      } else if (paytypes == 2) {
        _this.getbomn('')
      }
    }
    // console.log(Taro.getStorageSync('dateinfo').token+'token')
  }

  getbomn(code){
    var _this=this
    var state = _this.state
    var houesCount = state.copies_num
    var userName = state.userName
    var userPhone = state.userPhone
    var remark = state.remark
    var totalAmount=_this.state.copies_num*_this.state.res.basePrice

    if(code){
    	var payTypeId=125
    }
    else{
    	var payTypeId=10
    }
    var date = {
	  "code":code,
	  "payTypeId":payTypeId,
	  "projectId":_this.$router.preload.activityId,
	  "totalAmount":totalAmount,
	  "amount": 0,
	  "shopId":Taro.getStorageSync('shopId'),
	  userName:userName,
	  userPhone:userPhone,
	  remark:remark,
	  num:houesCount
	}
    if(this.state.verificationCode){
    	date.verificationCode=this.state.verificationCode
    }
    var url='/verify/papi/v1.9/consumption-order/createPay';
    Taro.showLoading({title: '报名中'})
    CommonJs.ajaxRequest(url,date,'POST',function(ret){
        // console.log(JSON.stringify(res)+'//11111')
        var dateinfo = Taro.getStorageSync('dateinfo');
	  	var str=date.projectId+","+dateinfo.qid;
	  	CommonJs.getFootPrint('Buy',2,str);
        Taro.hideLoading()
        if (totalAmount == 0) {
            Taro.showToast({
              title:'报名成功',
              icon: 'success',
              duration: 2000
            })
            _this.certificate(ret.data.consumeOrder.serialno)
        }
        else {
        	if(date.payTypeId==125){
        		var timeStamp = ret.data.timeStamp
	          var nonceStr = ret.data.nonceStr
	          var packageValue = ret.data.packageValue
	          var signType = ret.data.signType
	          var paySign = ret.data.paySign
	          Taro.requestPayment({
	          	appId:ret.data.appId,
	            timeStamp:timeStamp,
	            nonceStr: nonceStr,
	            package: packageValue,
	            signType: signType,
	            paySign: paySign,
	            success(res) {
	              _this.certificate(ret.data.consumeOrder.serialno)

	            },
	            fail() {
	              Taro.showToast({
	                title:'支付失败',
	                icon: 'none',
	                duration: 2000
	              })
	            }
	          })
        	}
        }
    },'wfw')
  }

  payNow(totalAmount, orderId, code){
    var _this=this
    var paytypes = _this.state.paytypes
    if (paytypes == 1) {
      var date = {
        payAmount:totalAmount,
        orderId:orderId,
        payTypeId:'125',
        code: code
      }
    } else if (paytypes == 2) {
      var payPasswords = _this.state.paypwd
      var payPassword = payPasswords.join('')
      var date = {
        payAmount:totalAmount,
        orderId:orderId,
        payTypeId:'10',
        payPassword:payPassword
      }
    }
    // console.log(JSON.stringify(date)+'//3333333333')
    Taro.showLoading({title: '支付中',mask: true})
    CommonJs.ajaxRequest('/consume/payOrder',date,'GET',function(ret){
    	if(date.payAmount==0){
    		_this.certificate()
    	}
    	else{
	        if (paytypes == 1) {
	          // console.log(JSON.stringify(ret))
	          var timeStamp = ret.content.timeStamp
	          var nonceStr = ret.content.nonceStr
	          var packageValue = ret.content.packageValue
	          var signType = ret.content.signType
	          var paySign = ret.content.paySign
	          Taro.requestPayment({
	          	appId:ret.content.appId,
	            timeStamp:timeStamp,
	            nonceStr: nonceStr,
	            package: packageValue,
	            signType: signType,
	            paySign: paySign,
	            success(res) {
	              _this.certificate()
	              // var pages = Taro.getCurrentPages()
	              // var projectId = _this.$router.preload.activityId
	              // if(pages.length > 1){
	              //   var prePage = pages[pages.length - 2]
	              //   prePage.setState({
	              //     projectId: projectId,
	              //     boshi: 2
	              //   })
	              //   Taro.navigateBack({
	              //     delta: 1
	              //   })
	              // }
	            },
	            fail() {
	              Taro.showToast({
	                title:'支付失败',
	                icon: 'none',
	                duration: 2000
	              })
	            }
	          })
	        } else if (paytypes == 2) {
	          // console.log(JSON.stringify(ret)+'1111')
	          if (ret) {
	            if (ret.code != 300) {
	              Taro.hideLoading()
	              Taro.showToast({
	                title:'支付成功',
	                icon: 'success',
	                duration: 1500,
	                mask: true
	              })
	              setTimeout(() => { _this.certificate() }, 1500)
	            } else {
	              Taro.hideLoading()
	              Taro.showModal({
	                title: '操作失败',
	                content: ret.msg,
	                cancelText: '重试',
	                showCancel: false,
	                confirmText: '重试',
	                success:function(res){
	                  // console.log(JSON.stringify(res))
	                  if (res.cancel) {
	                    _this.setState({
	                      paypwd:[],
	                      paypwdlen:0
	                    })
	                  }
	                  if (res.confirm) {
	                    _this.setState({
	                      paypwd:[],
	                      paypwdlen:0
	                    })
	                  }
	                }
	              })
	            }
	          }
	        }
	    }
    },'noloading','noret')
  }

  certificate(orderSerialno){
    //弹出活动凭证吗
    
    Taro.showLoading({title: '获取活动凭证',mask: true})
    var url='/verify/papi/v1.9/consumption-order/verifyCode/'+orderSerialno
    CommonJs.ajaxRequest(url,'','GET',function(res){
        // console.log(JSON.stringify(res)+'//444444')
        let content = '报名成功，活动凭证码为：'+res.data.verifyCode+'，请截屏保存以便参加活动时出示此凭证'
        Taro.showModal({
	      title: '活动凭证码',
	      content: content,
	      showCancel: false,
	      success(res){
	       	CommonJs.openTo('/pages/my/consumer');
	      }
	    })
    },'wfw')
  }

 

  getdata(){
    //活动详情
    // console.log(this.$router.preload.activityId)
    var _this=this;
    var date = {
        projectId:_this.$router.preload.activityId
    }
    var url='/verify/papi/v1.9/project/'+_this.$router.preload.activityId
    CommonJs.ajaxRequest(url,'','GET',function(res){
        _this.setState({
          res: res.data,
          isload: 1
        });
        Taro.setNavigationBarTitle({title:res.data.name+"报名"})
        _this.getmember();
    },'wfw')
  }

  open(url){
  	CommonJs.openTo(url);
  }

  getusername(event){
    this.setState({
        userName: event.target.value
    })
  }

  getuserphone(event){
    this.setState({
        userPhone: event.target.value
    })
  }

  getremark(event){
    this.setState({
        remark: event.target.value
    })
  }
  payment(event){
    var _this = this
    // console.log(JSON.stringify(event))
    var checked = event.currentTarget.dataset.type
    var bmtetlist = _this.state.bmtetlist//获取Json数组
    for (var i = 0; i < bmtetlist.length;i++){
      if (bmtetlist[i].id == checked){
        bmtetlist[i].toucheck = true;//当前点击的位置为true即选中
      }
      else{
        bmtetlist[i].toucheck = false;//其他的位置为false
      }
    }
    _this.setState({
      bmtetlist:bmtetlist,
      paytypes:checked
    })
  }
  closepay(){
    var _this = this
    _this.setState({
      zftype:0
    })
  }
  inputNum(type,event){
    var _this = this
    // console.log(JSON.stringify(event))
    // console.log(type)
    var paypwd = _this.state.paypwd
    if (type == 1) {
      var paypwdlen = paypwd.length
      if (paypwdlen < 6) {
        var num = event.target.dataset.number
        paypwd.push(num)
        var paypwdlen = paypwd.length
        _this.setState({
          paypwd:paypwd,
          paypwdlen:paypwdlen
        },function(){
          if (paypwdlen == 6) {
            //支付
            var houesCount = _this.state.copies_num
            var totalAmount = _this.state.res.basePrice * houesCount
            var orderId = _this.state.orderId
            _this.payNow(totalAmount, orderId, '')
          }
        })
      }
    } else if (type == 2) {
      paypwd.pop()
      var paypwdlen = paypwd.length
      _this.setState({
        paypwd:paypwd,
        paypwdlen:paypwdlen
      })
    }
    // console.log(JSON.stringify(_this.state.paypwd))
  }
  chooseyhq(){
    if(this.state.yhqname){
      var _this=this;
      Taro.showActionSheet({
        itemList: ['选择优惠券', '不使用优惠券'],
        success(res){
          //console.log(JSON.stringify(res))
          if(res.tapIndex==0){
            _this.$preload({
            	byfrom:'activity',
            	payAmount:_this.state.copies_num*_this.state.res.basePrice,
            	shopId:Taro.getStorageSync('shopId'),
            	number:this.state.copies_num
            })
            _this.open("/pages/coupon/coupon");

          }
          else if(res.tapIndex==1){
            var ytotal=_this.state.ytotal;
            _this.setState({
              verificationCode:'',
              yhqname:'',
            })
          }
        }
      })
    }
    else{
      this.$preload({
      	byfrom:'activity',
		payAmount:this.state.copies_num*this.state.res.basePrice,
		shopId:Taro.getStorageSync('shopId')
      })
      this.open("/pages/coupon/coupon");
    }

  }
  render () {
    const res = this.state.res
    const copies_num = this.state.copies_num
    const tuitable = this.state.tuitable
    const paypwdlen = this.state.paypwdlen
    const bmtetlist = this.state.bmtetlist
    const yhqname=this.state.yhqname
    const member=this.state.member
    //原来返回
    //<View className='qun-back' onClick={this.opendetails.bind(this,'/pages/activitydetails/activitydetails',this.$router.preload.activityId)}><Image className='qun-backimg' src={backwmall}></Image></View>
    return (
    	<View className='page' style={this.state.isload==1?'display:block':'display:none'}>
        <View className='qun-zffixed' style={this.state.zftype==1?'display:block':'display:none'}>
          <View className='qun-zfbotn'>
            <View className='section'>
              <View className='qun-zftite'>
                <Image className='qun-zfclose' onClick={this.closepay.bind(this)} src='https://minichat.g2ma.com/kedouimg/close1.png'></Image>
                <Text>请输入支付密码</Text>
                <Text></Text>
              </View>
              <View className='qun-zfmima'>
                <View className='qun-zfkuan'>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 1 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 2 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 3 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 4 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 5 ? '●' : ''} type='text' disabled='true'/>
                  <Input className='qun-zfmmyn' value={paypwdlen >= 6 ? '●' : ''} type='text' disabled='true'/>
                </View>
              </View>
              <View className='qun-zfwanji'><Text onClick={this.buzhichi.bind(this)}>忘记密码?</Text></View>
              <View className='tui-table-view'>
                {tuitable.map((item, index) => (
                <View className={item.tuibg ? 'tui-col-3 tui-bg' : 'tui-col-3'} dataNumber={item.number} onClick={this.inputNum.bind(this,item.click)}>
                  {item.innerhtml ?
                    <Image className='qun-zfdel' src='https://minichat.g2ma.com/kedouimg/del.png'></Image>
                    :
                    item.number
                  }
                </View>
                ))}
              </View>
            </View>
          </View>
        </View>
	      <View className='qun-banner qun-bm'>

	       <View className='qun-tetu'>
	       	<Image className='qun-bmimg' src={res.logo}></Image>
	       	<View className='qun-som'>
	       		<Text className='qun-jequ'>{res.name}</Text>
	       		<Text className='qun-bmdzi qun-jequ'>{res.activityAddress}</Text>
	       	</View>
	       </View>
	       <View className='qun-bmgue'>
	       	<View className='qun-gueli'>
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>预定份数</Text>
	       		</View>
	       		<View className='qun-bmsuj qun-jagnrg'>
	       			<View className='qun-jagn'>
	       				<Image className='qun-bmjan' onClick={this.addandsubtract.bind(this,0)} src={copies_img}></Image>
	       				<Input className='qun-bmfesu' type="number" value={copies_num} disabled='true'/>
	       				<Image className='qun-bmjan' onClick={this.addandsubtract.bind(this,1)} src='https://minichat.g2ma.com/kedouimg/icon20.png'></Image>
	       			</View>
	       		</View>
	       	</View>
	       	<View className='qun-gueli .qun-guelibrto'>
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>订单价格</Text>
	       		</View>
	       		<View className='qun-bmsuj qun-jagnrg qun-color1'>
	       			<View className='qun-jagn qun-color1' style="float:right;">
	       				￥{res.basePrice * copies_num/100}
	       			</View>
	       		</View>
	       	</View>
	       	<View className='qun-gueli' onClick={this.chooseyhq.bind(this)} style="border-top:1PX solid #eee;">
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>选择优惠券</Text>
	       		</View>
	       		<View className='qun-bmsuj qun-jagnrg' style="color:#999">
	       			{yhqname?yhqname:'请选择'}
	       		</View>
	       	</View>
	       	<View className='qun-gueli' style={member?'border-top:1PX solid #eee;':'display:none;'}>
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>会员折扣</Text>
	       		</View>
	       		<View className='qun-bmsuj qun-jagnrg' style="color:#999">
	       			{member.level.name}/{member.level.discount/100}折
	       		</View>
	       	</View>
	       </View>

	       <View className='qun-bmgue'>
	       	<View className='qun-gueli'>
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>联系人姓名</Text>
	       		</View>
	       		<View className='qun-bmsuj'>
	       			<View className='qun-jagn'>
	       				<Input className='' maxLength='10' onInput={this.getusername.bind(this)} type='text' placeholder='请输入联系人姓名'/>
	       			</View>
	       		</View>
	       	</View>
	       	<View className='qun-gueli .qun-guelibrto'>
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>联系方式</Text>
	       		</View>
	       		<View className='qun-bmsuj'>
	       			<View className='qun-jagn'>
	       				<Input className='' maxLength='11' onInput={this.getuserphone.bind(this)} type='number' placeholder='请输入联系方式'/>
	       			</View>
	       		</View>
	       	</View>
	       	<View className='qun-gueli .qun-guelibrto'>
	       		<View className='qun-bmzlo'>
	       			<Text className='qun-bmsuwn'>备注</Text>
	       		</View>
	       		<View className='qun-bmsuj'>
	       			<View className='qun-jagn'>
	       				<Input className='' maxLength='150' onInput={this.getremark.bind(this)} type='text' placeholder='请输入备注'/>
	       			</View>
	       		</View>
	       	</View>
	       </View>
	       <View className='qun-bmgue'>
	       	<View className='qun-bmtet'>支付方式</View>
          {bmtetlist.map((item, index) => (
	       	<View classNme='qun-zifans' onClick={this.payment.bind(this)} dataType={item.id}>
	       		<View className='qun-zifuli'>
	       			<View className='qun-fasi'>
	       				<Image className='qun-fsimg' src={item.touimg}></Image>
	       				<View className='qun-wexm'>
	       					<Text>{item.toutype}</Text>
	       					<Text className='qun-wexsy'>{item.touname}</Text>
	       				</View>
	       			</View>
	       			<Image className='qun-bmbgtu' src={item.toucheck ? 'https://minichat.g2ma.com/kedouimg/icon24.png' : 'https://minichat.g2ma.com/kedouimg/icon23.png'}></Image>
	       		</View>
	       	</View>
          ))}
	       </View>
	       <View className='qun-bmljzf' onClick={this.lijipay.bind(this)}>立即支付</View>

	      </View>
      </View>
    )
  }
}
